package logic

import (
	"context"
	"encoding/json"
	"fmt"
	"time"
	"zhaowei/models/cache"
	"zhaowei/models/mysql"

	"zhaowei/baidurpc/baidurpc"
	"zhaowei/baidurpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ChartsLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewChartsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ChartsLogic {
	return &ChartsLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ChartsLogic) Charts(in *baidurpc.ChartsRequest) (*baidurpc.ChartsResponse, error) {
	// todo: add your logic here and delete this line
	var a []mysql.Post
	key := fmt.Sprintf("list")
	get, _ := cache.Rdb.Get(cache.Ctx, key).Result()
	if get != "" {
		json.Unmarshal([]byte(get), &a)
	} else {
		mysql.DB.Debug().Order("like desc").Find(&a)
		jsonData, _ := json.Marshal(&a)
		cache.Rdb.Set(cache.Ctx, key, jsonData, time.Minute*30)
	}
	offset := (in.Page - 1) * in.Size

	mysql.DB.Debug().Offset(int(offset)).Limit(int(in.Size)).Find(&a)
	var b []*baidurpc.ChartsList
	for _, c := range a {
		list := baidurpc.ChartsList{
			UserId: int64(c.UserId),
			Name:   c.Name,
			Image:  c.Image,
			Like:   int64(c.Like),
			BarId:  int64(c.BarId),
			Id:     int64(c.ID),
		}
		b = append(b, &list)
	}
	return &baidurpc.ChartsResponse{
		List: b,
	}, nil
}
